package com.atguigu.gmall.product.controller;

import com.alibaba.nacos.common.util.ClassUtils;
import com.atguigu.gmall.product.client.common.result.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

    @Value("${imgUrl}")
    private  String imgUrl;

    @ApiOperation("上传文件")
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{
        //上传文件
        //1.初始化配置文件 流只能读取绝对路径 不认识相对路径
        String path = ClassUtils.getDefaultClassLoader()
                .getResource("fdfs_client.conf").getPath();
        ClientGlobal.init(path);
        //2.连接Tracker跟踪器
        TrackerClient trackerClient = new TrackerClient();
        //TrackerServer 存储节点的IP及端口号
        TrackerServer trackerServer = trackerClient.getConnection();
        //3.连接储存节点
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);
        //扩展名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        //4.上传文件
        String fileId = storageClient1.upload_file1(
                file.getBytes(),
                ext,
                null
        );
        System.out.println(fileId);
        return Result.ok(imgUrl+fileId);
    }
}
